package jnpf.base.util;

import cn.hutool.http.HttpConfig;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

/**
 * @description: http请求工具类
 * @author: duanxu
 * @create: 2025-01-20 11:10
 **/
@Slf4j
public class HttpUtil {

    private static HttpConfig httpConfig;

    static {
        httpConfig = HttpConfig.create()
                .setReadTimeout(30000)
                .setConnectionTimeout(30000);
    }

    public static String httpGet(String url) {
        HttpRequest get = cn.hutool.http.HttpUtil.createGet(url);
        get.setConfig(httpConfig);
        try {
            HttpResponse response = get.execute();
            JSONObject result = JSONObject.parseObject(response.body());
            // 结果判定
            httpResultProcess(result);
            // 结果解析
            return JSONObject.toJSONString(result.get("data"));
        } catch (Exception e) {
            log.error("httpGet请求失败", e);
            return null;
        }
    }

    private static void httpResultProcess(JSONObject jsonObject) {
        Integer code = jsonObject.getInteger("code");
        if (code != 0) {
            throw new RuntimeException(jsonObject.getString("msg"));
        }
    }

}
